import csv
from django.core.management.base import BaseCommand
from app1.models import Meta  # 确保导入正确的模型

class Command(BaseCommand):
    help = 'Import data from a CSV file into the Meta database'

    def add_arguments(self, parser):
        parser.add_argument('file_path', type=str, help='The path to the CSV file')
        parser.add_argument('subcluster', type=str, help='The subcluster value to be added')

    def handle(self, *args, **kwargs):
        file_path = kwargs['file_path']
        subcluster = kwargs['subcluster']
        self.import_csv_to_db(file_path, subcluster)

    def import_csv_to_db(self, file_path, subcluster):
        # 检查数据库中是否已存在相同的 subcluster 数据
        if Meta.objects.filter(subcluster=subcluster).exists():
            self.stdout.write(self.style.WARNING('数据已存在，导入操作被取消。'))
            return  # 直接返回，不再执行后续操作
        # 准备批量插入的数据列表
        metas_to_create = []
        with open(file_path, mode='r') as file:
            reader = csv.DictReader(file)
            for index, row in enumerate(reader):
                order = index + 1
                cell_states = row.get('cell_states', row['cell_type1'])

                # Meta.objects.create(
                #     subcluster=subcluster,
                #     oindex=row['oindex'],  # 将 oindex 字段插入数据库
                #     sample=row['sample'],
                #     donor=row['donor'],
                #     age=row['age'],
                #     condition=row['condition'],
                #     region=row['region'],
                #     race=row['race'],
                #     sex=row['sex'],
                #     data_name=row['data_name'],
                #     cell_type1=row['cell_type1'],
                #     UMAP_1=row['UMAP_1'],
                #     UMAP_2=row['UMAP_2'],
                #     order=order,
                #     cell_states=cell_states
                # )
                # 创建 Meta 实例并添加到列表中
                metas_to_create.append(
                    Meta(
                        subcluster=subcluster,
                        oindex=row['oindex'],  # 将 oindex 字段插入数据库
                        sample=row['sample'],
                        donor=row['donor'],
                        age=row['age'],
                        condition=row['condition'],
                        region=row['region'],
                        race=row['race'],
                        sex=row['sex'],
                        data_name=row['data_name'],
                        cell_type1=row['cell_type1'],
                        UMAP_1=row['UMAP_1'],
                        UMAP_2=row['UMAP_2'],
                        order=order,
                        cell_states=cell_states
                    )
                )
        # 批量插入数据
        Meta.objects.bulk_create(metas_to_create)
        self.stdout.write(self.style.SUCCESS('Data imported successfully!'))
